import React, { useState } from "react";
import {
  Card,
  Form,
  Button,
  Col,
  Row,
  Input,
  Upload,
  Avatar,
  Space,
  message,
} from "antd";
import { UploadOutlined, EditOutlined } from "@ant-design/icons";
import { agentEdit, agentAvatarEdit } from "../../services/auth";
import { getToken, setToken } from "../../utils/auth";

function PersonalManagement() {
  const [avatar, setAvatar] = useState();
  const [file, setFile] = useState("");
  const [user, setUser] = useState(JSON.parse(getToken()));
  const formRef = React.createRef();
  const normFile = (e) => {
    console.log("Upload event:", e);
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };
  const onFinish = (values) => {
    const { id, name, phone, email } = values;
    let agent = { id, name, phone, email, company_id: user.company_id };
    agentEdit(agent);
    if (avatar) {
      console.log("修改图片");
      let formData = new FormData();
      formData.append("id", id);
      formData.append("file", avatar);
      agentAvatarEdit(formData).then(
        (response) => {
          if (response.data.result === "success") {
            setToken(JSON.stringify(response.data.user));
            setUser(JSON.stringify(response.data.user));
            message.success("修改成功");
          } else {
            message.info("修改失败，请重试");
          }
        },
        (error) => {
          console.log("数据获取失败", error);
        }
      );
    } else {
      console.log("没动不需修改");
    }
  };
  const onReset = () => {
    if (formRef.current) {
      formRef.current.setFieldsValue({
        id: user.id,
        name: user.name,
        phone: user.phone,
        email: user.email,
      });
    }
    setFile("");
  };
  return (
    <Card
      title="基本设置"
      extra={
        <Button
          type="link"
          size="small"
          icon={<EditOutlined />}
          style={{ fontWeight: "bold" }}
        >
          修改密码
        </Button>
      }
    >
      <Form
        layout="vertical"
        hideRequiredMark
        onFinish={onFinish}
        ref={formRef}
      >
        <Row gutter={24}>
          <Col span={8}>
            <Form.Item name="id" label="账号" initialValue={user.id}>
              <Input disabled />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="name"
              label="姓名"
              initialValue={user.name}
              rules={[{ required: true, message: "请输入姓名" }]}
            >
              <Input />
            </Form.Item>
          </Col>
          <Col span={8} style={{ textAlign: "center" }}>
            <Avatar
              id="preview"
              size={{
                xs: 24,
                sm: 32,
                md: 40,
                lg: 64,
                xl: 80,
                xxl: 100,
              }}
              src={
                file === "" ? `http://imgdic.natapp1.cc${user.avatar}` : file
              }
            />
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={8}>
            <Form.Item name="phone" label="电话" initialValue={user.phone}>
              <Input />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item name="email" label="邮箱" initialValue={user.email}>
              <Input />
            </Form.Item>
          </Col>
          <Col span={8} style={{ textAlign: "center" }}>
            <Form.Item
              name="avatar"
              valuePropName="fileList"
              getValueFromEvent={normFile}
            >
              <Upload
                maxCount={1}
                showUploadList={false}
                beforeUpload={(file) => {
                  setAvatar(file);
                  //1.创建文件读取对象
                  var reader = new FileReader();
                  //2.读取用户选择的文件
                  reader.readAsDataURL(file);
                  //3.监听文件下载(读取)状况
                  reader.onload = function () {
                    //把reader.result给img标签添加属性src
                    console.log(reader);
                    setFile(reader.result);
                  };
                  return false;
                }}
              >
                <Button icon={<UploadOutlined />}>上传头像</Button>
              </Upload>
            </Form.Item>
          </Col>
        </Row>
        <Form.Item
          style={{
            textAlign: "right",
          }}
        >
          <br />
          <Space>
            <Button onClick={onReset}>重置</Button>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </Card>
  );
}

export default PersonalManagement;
